'use client';

import { useState, useEffect, useCallback, useMemo } from 'react';
import { Search, X, FileText, Code, Book, Users, Zap } from 'lucide-react';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
import { useRouter } from 'next/navigation';

// 搜索结果类型定义
interface SearchResult {
  id: string;
  title: string;
  description: string;
  url: string;
  type: 'page' | 'docs' | 'code' | 'solution' | 'case';
  category: string;
  keywords: string[];
  content?: string;
}

// 搜索数据 - 实际项目中应该从API获取
const SEARCH_DATA: SearchResult[] = [
  // 主要页面
  {
    id: 'home',
    title: 'CActor框架 - 高性能Actor模型开发框架',
    description:
      '新一代高性能Actor模型开发框架，专为金融、电商等高并发场景设计',
    url: '/',
    type: 'page',
    category: '主页',
    keywords: ['actor', '高性能', '并发', '框架', '仓颉'],
    content: 'CActor是基于仓颉语言开发的新一代高性能Actor模型开发框架',
  },
  {
    id: 'solutions',
    title: '解决方案',
    description: '针对不同行业和场景的专业解决方案',
    url: '/solutions',
    type: 'page',
    category: '解决方案',
    keywords: ['解决方案', '金融', '支付', '交易', '风控'],
    content: '高频交易、分布式账本、实时支付、智能风控等专业解决方案',
  },
  {
    id: 'hft-solution',
    title: '高频交易系统解决方案',
    description: '微秒级延迟的高频交易系统，支持百万级TPS',
    url: '/solutions/high-frequency-trading',
    type: 'solution',
    category: '金融解决方案',
    keywords: ['高频交易', 'HFT', '低延迟', 'TPS', '金融'],
    content: '专为高频交易设计的超低延迟系统架构',
  },
  {
    id: 'payment-solution',
    title: '实时支付处理系统',
    description: '高可用的实时支付处理解决方案',
    url: '/solutions/real-time-payment',
    type: 'solution',
    category: '支付解决方案',
    keywords: ['支付', '实时', '高可用', '流处理'],
    content: '基于流处理架构的实时支付系统',
  },
  {
    id: 'risk-solution',
    title: '智能风控系统',
    description: 'AI驱动的实时风险控制系统',
    url: '/solutions/intelligent-risk-control',
    type: 'solution',
    category: '风控解决方案',
    keywords: ['风控', 'AI', '机器学习', '实时决策'],
    content: 'AI驱动的智能风险控制和反欺诈系统',
  },
  // 文档
  {
    id: 'docs-quick-start',
    title: '快速开始',
    description: 'CActor框架快速入门指南',
    url: '/docs/quick-start',
    type: 'docs',
    category: '文档',
    keywords: ['快速开始', '入门', '安装', '配置'],
    content: '快速安装和配置CActor框架的完整指南',
  },
  {
    id: 'docs-api',
    title: 'API参考',
    description: '完整的API文档和参考',
    url: '/docs/api-reference',
    type: 'docs',
    category: '文档',
    keywords: ['API', '参考', '文档', '接口'],
    content: 'CActor框架的完整API参考文档',
  },
  // 案例研究
  {
    id: 'case-bank-hft',
    title: '某大型银行高频交易系统',
    description: '帮助银行实现微秒级交易延迟的成功案例',
    url: '/cases/bank-hft',
    type: 'case',
    category: '案例研究',
    keywords: ['银行', '高频交易', '案例', '成功'],
    content: '大型银行高频交易系统的实施案例和效果',
  },
  {
    id: 'case-payment',
    title: '支付公司实时处理系统',
    description: '支付公司使用CActor实现高并发处理',
    url: '/cases/payment-system',
    type: 'case',
    category: '案例研究',
    keywords: ['支付', '实时处理', '高并发', '案例'],
    content: '支付公司实时交易处理系统的成功实施',
  },
];

interface GlobalSearchProps {
  isOpen: boolean;
  onClose: () => void;
}

/**
 * 全站搜索组件
 */
export function GlobalSearch({ isOpen, onClose }: GlobalSearchProps) {
  const [query, setQuery] = useState('');
  const [selectedIndex, setSelectedIndex] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const router = useRouter();

  // 搜索结果
  const searchResults = useMemo(() => {
    if (!query.trim()) return [];

    const normalizedQuery = query.toLowerCase().trim();

    return SEARCH_DATA.filter(item => {
      // 标题匹配
      if (item.title.toLowerCase().includes(normalizedQuery)) return true;
      // 描述匹配
      if (item.description.toLowerCase().includes(normalizedQuery)) return true;
      // 关键词匹配
      if (
        item.keywords.some(keyword =>
          keyword.toLowerCase().includes(normalizedQuery)
        )
      )
        return true;
      // 内容匹配
      if (item.content?.toLowerCase().includes(normalizedQuery)) return true;

      return false;
    })
      .sort((a, b) => {
        // 标题完全匹配优先
        const aExactTitle = a.title.toLowerCase() === normalizedQuery;
        const bExactTitle = b.title.toLowerCase() === normalizedQuery;
        if (aExactTitle && !bExactTitle) return -1;
        if (!aExactTitle && bExactTitle) return 1;

        // 标题包含查询词优先
        const aTitleMatch = a.title.toLowerCase().includes(normalizedQuery);
        const bTitleMatch = b.title.toLowerCase().includes(normalizedQuery);
        if (aTitleMatch && !bTitleMatch) return -1;
        if (!aTitleMatch && bTitleMatch) return 1;

        return 0;
      })
      .slice(0, 10); // 限制结果数量
  }, [query]);

  // 键盘导航
  const handleKeyDown = useCallback(
    (e: KeyboardEvent) => {
      if (!isOpen) return;

      switch (e.key) {
        case 'ArrowDown':
          e.preventDefault();
          setSelectedIndex(prev =>
            prev < searchResults.length - 1 ? prev + 1 : 0
          );
          break;
        case 'ArrowUp':
          e.preventDefault();
          setSelectedIndex(prev =>
            prev > 0 ? prev - 1 : searchResults.length - 1
          );
          break;
        case 'Enter':
          e.preventDefault();
          if (searchResults[selectedIndex]) {
            handleResultClick(searchResults[selectedIndex]);
          }
          break;
        case 'Escape':
          onClose();
          break;
      }
    },
    [isOpen, searchResults, selectedIndex, onClose]
  );

  useEffect(() => {
    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [handleKeyDown]);

  // 重置选中索引
  useEffect(() => {
    setSelectedIndex(0);
  }, [searchResults]);

  // 处理结果点击
  const handleResultClick = (result: SearchResult) => {
    router.push(result.url);
    onClose();
    setQuery('');
  };

  // 获取类型图标
  const getTypeIcon = (type: SearchResult['type']) => {
    switch (type) {
      case 'page':
        return <FileText className="w-4 h-4" />;
      case 'docs':
        return <Book className="w-4 h-4" />;
      case 'code':
        return <Code className="w-4 h-4" />;
      case 'solution':
        return <Zap className="w-4 h-4" />;
      case 'case':
        return <Users className="w-4 h-4" />;
      default:
        return <FileText className="w-4 h-4" />;
    }
  };

  // 获取类型颜色
  const getTypeColor = (type: SearchResult['type']) => {
    switch (type) {
      case 'page':
        return 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200';
      case 'docs':
        return 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200';
      case 'code':
        return 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200';
      case 'solution':
        return 'bg-orange-100 text-orange-800 dark:bg-orange-900 dark:text-orange-200';
      case 'case':
        return 'bg-pink-100 text-pink-800 dark:bg-pink-900 dark:text-pink-200';
      default:
        return 'bg-gray-100 text-gray-800 dark:bg-gray-900 dark:text-gray-200';
    }
  };

  // 高亮匹配文本
  const highlightText = (text: string, query: string) => {
    if (!query.trim()) return text;

    const regex = new RegExp(
      `(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`,
      'gi'
    );
    const parts = text.split(regex);

    return parts.map((part, index) =>
      regex.test(part) ? (
        <mark
          key={index}
          className="bg-yellow-200 dark:bg-yellow-800 px-0.5 rounded"
        >
          {part}
        </mark>
      ) : (
        part
      )
    );
  };

  return (
    <Dialog open={isOpen} onOpenChange={onClose}>
      <DialogContent className="max-w-2xl max-h-[80vh] p-0 overflow-hidden">
        <DialogHeader className="p-4 pb-0">
          <DialogTitle className="sr-only">全站搜索</DialogTitle>
        </DialogHeader>

        {/* 搜索输入框 */}
        <div className="relative p-4">
          <Search className="absolute left-7 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
          <Input
            value={query}
            onChange={e => setQuery(e.target.value)}
            placeholder="搜索文档、解决方案、案例..."
            className="pl-10 pr-10 h-12 text-lg border-0 focus-visible:ring-0 bg-gray-50 dark:bg-gray-900"
            autoFocus
          />
          {query && (
            <button
              onClick={() => setQuery('')}
              className="absolute right-7 top-1/2 -translate-y-1/2 p-1 hover:bg-gray-200 dark:hover:bg-gray-700 rounded"
            >
              <X className="w-4 h-4 text-gray-400" />
            </button>
          )}
        </div>

        {/* 搜索结果 */}
        <div className="max-h-96 overflow-y-auto">
          {query.trim() && (
            <div className="px-4 py-2 text-sm text-gray-500 dark:text-gray-400 border-t">
              找到 {searchResults.length} 个结果
            </div>
          )}

          {searchResults.length > 0 ? (
            <div className="py-2">
              {searchResults.map((result, index) => (
                <button
                  key={result.id}
                  onClick={() => handleResultClick(result)}
                  className={cn(
                    'w-full px-4 py-3 text-left hover:bg-gray-50 dark:hover:bg-gray-800 transition-colors',
                    index === selectedIndex && 'bg-gray-50 dark:bg-gray-800'
                  )}
                >
                  <div className="flex items-start gap-3">
                    <div className="flex-shrink-0 mt-1">
                      {getTypeIcon(result.type)}
                    </div>

                    <div className="flex-1 min-w-0">
                      <div className="flex items-center gap-2 mb-1">
                        <h3 className="font-medium text-gray-900 dark:text-gray-100 truncate">
                          {highlightText(result.title, query)}
                        </h3>
                        <Badge
                          variant="secondary"
                          className={cn('text-xs', getTypeColor(result.type))}
                        >
                          {result.category}
                        </Badge>
                      </div>

                      <p className="text-sm text-gray-600 dark:text-gray-400 line-clamp-2">
                        {highlightText(result.description, query)}
                      </p>

                      {result.keywords.length > 0 && (
                        <div className="flex flex-wrap gap-1 mt-2">
                          {result.keywords.slice(0, 3).map(keyword => (
                            <span
                              key={keyword}
                              className="inline-block px-2 py-0.5 text-xs bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-300 rounded"
                            >
                              {keyword}
                            </span>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>
                </button>
              ))}
            </div>
          ) : query.trim() ? (
            <div className="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
              <Search className="w-8 h-8 mx-auto mb-2 opacity-50" />
              <p>未找到相关结果</p>
              <p className="text-sm mt-1">尝试使用不同的关键词</p>
            </div>
          ) : (
            <div className="px-4 py-8 text-center text-gray-500 dark:text-gray-400">
              <Search className="w-8 h-8 mx-auto mb-2 opacity-50" />
              <p>输入关键词开始搜索</p>
              <p className="text-sm mt-1">支持搜索文档、解决方案、案例等内容</p>
            </div>
          )}
        </div>

        {/* 快捷键提示 */}
        <div className="px-4 py-3 border-t bg-gray-50 dark:bg-gray-900">
          <div className="flex items-center justify-between text-xs text-gray-500 dark:text-gray-400">
            <div className="flex items-center gap-4">
              <span className="flex items-center gap-1">
                <kbd className="px-1.5 py-0.5 bg-white dark:bg-gray-800 border rounded text-xs">
                  ↑↓
                </kbd>
                导航
              </span>
              <span className="flex items-center gap-1">
                <kbd className="px-1.5 py-0.5 bg-white dark:bg-gray-800 border rounded text-xs">
                  Enter
                </kbd>
                选择
              </span>
              <span className="flex items-center gap-1">
                <kbd className="px-1.5 py-0.5 bg-white dark:bg-gray-800 border rounded text-xs">
                  Esc
                </kbd>
                关闭
              </span>
            </div>
          </div>
        </div>
      </DialogContent>
    </Dialog>
  );
}

/**
 * 搜索触发按钮
 */
export function SearchTrigger({
  onOpen,
  className,
}: {
  onOpen: () => void;
  className?: string;
}) {
  useEffect(() => {
    const handleKeyDown = (e: KeyboardEvent) => {
      // Cmd+K (Mac) 或 Ctrl+K (Windows/Linux)
      if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
        e.preventDefault();
        onOpen();
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [onOpen]);

  return (
    <button
      onClick={onOpen}
      className={cn(
        'flex items-center gap-2 px-3 py-2 text-sm text-gray-600 dark:text-gray-400',
        'bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700',
        'border border-gray-200 dark:border-gray-700 rounded-lg transition-colors',
        'min-w-[200px] justify-between',
        className
      )}
    >
      <div className="flex items-center gap-2">
        <Search className="w-4 h-4" />
        <span>搜索...</span>
      </div>
      <kbd className="px-1.5 py-0.5 text-xs bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-600 rounded">
        ⌘K
      </kbd>
    </button>
  );
}
